<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2022/9/6
 * Time: 22:47
 */

namespace App\Tools;


use Google\Service\AndroidPublisher;
use Illuminate\Support\Facades\Log;


class GooglePay
{
    static function googlePayVerify(string $receipt,string $signature):bool
    {
        $key =	"-----BEGIN PUBLIC KEY-----\n".
            chunk_split(config('pay.google.public_key'), 64,"\n").
            '-----END PUBLIC KEY-----';
        //using PHP to create an RSA key
        $key = openssl_get_publickey($key);
        //$signature should be in binary format, but it comes as BASE64.
        //So, I'll convert it.
        $signature = base64_decode($signature);
        //using PHP's native support to verify the signature
        $result = openssl_verify(
            $receipt,
            $signature,
            $key,
            OPENSSL_ALGO_SHA1);
        if (0 === $result)
        {
            return false;
        }
        else if (1 !== $result)
        {
            return false;
        }
        else
        {
            return true;
        }

    }

    static function payV3($orderId, $productId, $token)
    {
        //1. 通过我们自己的orderId查到订单数据, 对于订单状态进行各种判断
        //2. 通过packagename productid token去google后台获取订单数据
        //$productId = "com.test.rmb998"; //通过orderId从我们数据库查到的

        $google_client = new \Google_Client();
        
        $google_client->setAuthConfig(json_decode(config('pay.google.auth_config'), true));
        $google_client->useApplicationDefaultCredentials();
        $google_client->addScope(\Google_Service_AndroidPublisher::ANDROIDPUBLISHER);
        $androidPublishService = new \Google_Service_AndroidPublisher($google_client);
        $result = $androidPublishService->purchases_products->get(
            "com.jxfq.dalle",
            $productId,
            $token
        );

        //客户端可以把字段obfuscatedExternalAccountId 透传为我们自己的订单ID, 用于验证google传回来的订单是否是我们需要的订单, 可能没有太大必要
        //if ($result->getObfuscatedExternalProfileId() != $orderId)
        //{
		//	Log::info("googleNotify_payV3", ['orderid' => $orderId, 'result' => $result]);
        //    return false;
        //}
		$sOrderIDOfReceipt = $result->getObfuscatedExternalProfileId();

        //3. 订单状态是支付成功. 进行发货处理, 同时在处理一下我们自己记录的订单数据
        //purchaseState  0. Purchased 1. Canceled 2. Pending
        if($result->purchaseState == 0)
        {
            //consumptionState 0. Yet to be consumed 1. Consumed
            //如果还未消费需要调用消费接口(这步可能客户端在做, 先注释掉)
            /* if ($result->consumptionState == 0)
             {
                 $androidPublishService->purchases_products->acknowledge(
                     self::PackageName,
                     $payOrder[PayAttr::Pay_Product_ID],
                     $token,
                     new ProductPurchasesAcknowledgeRequest((array)$result->toSimpleObject())
                 );
             }*/

            /**
             * 这里要有支付成功发货的逻辑. 同时标记该订单已经支付完成
             */

            //return true;

			if(!empty($sOrderIDOfReceipt)){
				return ['status' => true, 'order_id' => $sOrderIDOfReceipt];
			}else{
				return ['status' => true, 'order_id' => $orderId];
			}
		}else{
			Log::info("googleNotify_purchaseState", ['orderid' => $orderId, 'result' => $result]);
		}

        return false;
    }

    /**
     * 获取google购买商品订单的状态信息
     */
    static function getGooglePurchaseOrderInfo($orderId, $productId, $token){

        $google_client = new \Google_Client();
        
        $google_client->setAuthConfig(json_decode(config('pay.google.auth_config'), true));
        $google_client->useApplicationDefaultCredentials();
        $google_client->addScope(\Google_Service_AndroidPublisher::ANDROIDPUBLISHER);
        $androidPublishService = new \Google_Service_AndroidPublisher($google_client);
        $result = $androidPublishService->purchases_products->get(
            "com.jxfq.dalle",
            $productId,
            $token
        );
        Log::info('Google-pay-info-'.$orderId, ['result'=>$result,'external_order_id'=>$result['orderId']]);

        return $result;

    }

    /**
     * 获取google订阅订单的状态信息
     */
    static function getGoogleSubscribeOrderInfo($orderId,$token){

        $google_client = new \Google_Client();

        $google_client->setAuthConfig(json_decode(config('pay.google.auth_config'), true));
        $google_client->useApplicationDefaultCredentials();
        $google_client->addScope(\Google_Service_AndroidPublisher::ANDROIDPUBLISHER);
        $androidPublishService = new \Google_Service_AndroidPublisher($google_client);
        $result = $androidPublishService->purchases_subscriptionsv2->get(
            'com.jxfq.dalle',
            $token
        );
        Log::info('Google-pay-subscribe-info-'.$orderId, [$result]);
        return $result;

    }

    static function payV4($packageName, $productId, $token)
    {
        $google_client = new \Google_Client();

        $google_client->setAuthConfig(json_decode(config('pay.google.auth_config'), true));
        $google_client->useApplicationDefaultCredentials();
        $google_client->addScope(\Google_Service_AndroidPublisher::ANDROIDPUBLISHER);
        $androidPublishService = new \Google_Service_AndroidPublisher($google_client);
        $result = $androidPublishService->purchases_subscriptionsv2->get(
            $packageName,
            $token
        );

        return $result;
    }

}